﻿#region copyright
//<copyright>
// Copyright(C) 2012 TrackerRealm Corporation
// This file is part of the open source project - Jazz. http://jazz.codeplex.com
// 
// Jazz is open software: you can redistribute it and/or modify it 
// under the terms of the GNU Affero General Public License (AGPL) as published by 
// the Free Software Foundation, version 3 of the License.
// 
// Jazz is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty 
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
//  See the GNU Affero General Public License (AGPL) for more details.
// 
// You should have received a copy of the GNU General Public 
// License along with Jazz.  If not, see <http://www.gnu.org/licenses/>.
//
// REMOVAL OF THIS NOTICE IS VIOLATION OF THE COPYRIGHT. 
//</copyright>
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;
using TrackerRealm.Jazz.Common;
using C = TrackerRealm.Jazz.Common.JazzConstants;

namespace TrackerRealm.Jazz.Client
{
    /// <summary>
    /// '<see cref="jUserBase"/>' describes a user. 
    /// <para>Users may have multiple profiles (see <see cref="jProfileBase"/>).
    /// </para> The roles for
    /// a user are contained a '<see cref="jProfileBase"/>' object.
    /// A user object always has a single default profile.
    /// <para>Typically the '<see cref="jUserBase"/>' class is used as a base class
    /// with more information about provided about the user in an inherited class.</para>
    /// </summary>
    [Root]
    [Jazz]
    public abstract class jUserBase: jNameUnique
    {
        //
        // Constructors
        //
        #region Constructor
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="name"></param>
        protected jUserBase(string name)
            : base(name)
        {
        }
        #endregion
        //
        //  Instance Methods and Properties
        //
        #region Profiles
        [BaseField]
        private jProfileBase[] profiles = jProfileBase.EmptyArray;
        /// <summary>
        /// 
        /// </summary>
        internal protected virtual IEnumerable<jProfileBase> _Profiles
        {
            get { return this.profiles.Select(p => p); } //Select prevents casting to array
            set 
            {
                jProfileBase[] pArray = value.ToArray();
                if (pArray.Distinct().Count() != pArray.Count())
                    throw new ArgumentException("Elements are not unique.", "value");
                if (pArray.Select<jProfileBase, string>(p => p.Name).Distinct().Count() != pArray.Select<jProfileBase, string>(p => p.Name).Count())
                    throw new ArgumentException("The names of the 'profiles' in this sequence are not unique.", "value");
                if (!pArray.Contains(defaultProfile))
                    throw new ArgumentException("The 'defaultProfile' must be a element in the enumerable.", "value");
                if (pArray.FirstOrDefault(p => !(p._User == null || p._User == this || p._User.IsEmpty)) != null)
                    throw new ArgumentException("Attempting to assign to a sequence profile that has at least 1 element associated with another user", "value");
                if (this.IsBound)
                {
                    pArray.Where(u => !u.IsBound).Foreach(u => this.ClientNexus.Bind(u));
                    if (pArray.FirstOrDefault(u => this.ClientNexus != u.ClientNexus) != null)
                        throw new ArgumentException("Attempting to set a 'role' that is bound to another client nexus.");
                    // need to bind roles
                }

                this.profiles = pArray;
            }
        }
        #endregion
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected internal override IEnumerable<jObject> _Children()
        {
            return this._Profiles;
        }
        
        #region IjUser Members
        
        /// <summary>
        /// 
        /// </summary>
        internal virtual jUserBase _User
        {
            get { return this; }
        }
        [BaseField]
        private jProfileBase defaultProfile;
        /// <summary>
        /// Returns the default profile for the user.
        /// </summary>
        internal protected jProfileBase _Profile
        {
            get { return this.defaultProfile; }
            set
            {
                if (!this.profiles.Contains(value))
                    this.profiles = this._Profiles.AddToSequence(value).ToArray();
                if (!(value._User == null || value._User == this))
                    throw new ArgumentException(string.Format(
                        "Attempting to set the 'default' profile with a profile that is associated with another user: '{0}'", value._User.Name), "value");
                this.defaultProfile = value;
                // need to check or set user
            }
        }
        #endregion

        #region Add/Remove profiles
        /// <summary>
        /// 
        /// </summary>
        /// <param name="profile"></param>
        protected void _AddProfile(jProfileBase profile)
        {
            this._Profiles = this._Profiles.AddToUniqueSequence(profile);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="profile"></param>
        protected void _RemoveProfile(jProfileBase profile)
        {
            if (profile == this._Profile)
                throw new ArgumentException("Can not remove the default profile from the collection.", "profile");
            this._Profiles = this._Profiles.RemoveFromSequence(profile);
            // improve code - should always be able to get empty instance
            if (this.ClientNexus == null)
                profile._User = null;
            profile._User = (jUserBase)this.ClientNexus.Cache.JClasses.Get(this.GetType()).EmptyInstance;
        }
        #endregion
        #region Workspace
        /// <summary>
        /// 
        /// </summary>
        public override jWorkspaceBase Workspace
        {
            get
            {
                return base.Workspace;
            }
            protected internal set
            {
                if(this.defaultProfile.Workspace == null)//wrong - need to set all members.
                    this.defaultProfile.Workspace = value;
                base.Workspace = value;
            }
        }
        #endregion
        
    }
}
